import { request } from '../utils/request';
import { api } from '../utils/config';

const { uploadUrl, uploadTokenUrl, downloadUrl } = api;

/**
 * 获取七牛上传TOKEN
 */
export async function getUploadToken(params) {
  return request(uploadTokenUrl, {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${params.token}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      bucket: params.bucket,
      insertOnly: params.insertOnly,
    }),
  });
}

/**
 * 上传文件到七牛
 * @param {*} file 待上传文件
 * @param {*} token 上传token
 * @param {*} prefix 前缀
 */
export async function uploadFile(file, token, prefix) {
  if (!file || file.size === 0) return null;
  let key = `${file.preview.split('/').pop()}.${file.name.split('.').pop()}`;
  if (prefix) {
    key = prefix + key;
  }

  const data = new FormData();
  data.append('key', key);
  data.append('token', token);
  data.append('file', file);
  data.append('x:filename', file.name);
  data.append('x:size', file.size);

  return request(uploadUrl, {
    method: 'POST',
    body: data,
  });
}

/**
 * 获取七牛private下载地址
 * @param {*} data
 */
export async function getDownloadUrl(data) {
  return request(downloadUrl, {
    method: 'POST',
    body: data,
  });
}
